package com.lh.utils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class GetLinkUtil {




    public static Answer<String> getLink(String string) {
        String urlStr = string; // 替换为目标HTTP链接
        StringBuilder result = new StringBuilder();
        try {
            URL url = new URL(urlStr);
            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法
            connection.setRequestMethod("GET");
            // 设置超时时间
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);

            // 获取响应码
            int responseCode = connection.getResponseCode();
            System.out.println("响应码: " + responseCode);

            // 判断请求是否成功
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 读取响应数据
                InputStream inputStream = connection.getInputStream();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(inputStream, "UTF-8")
                );

                String line;
                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }

                // 关闭资源
                reader.close();
                inputStream.close();
            } else {
                System.out.println("请求失败，响应码: " + responseCode);
            }

            // 断开连接
            connection.disconnect();

        } catch (Exception e) {
            e.printStackTrace();
        }
        // 输出结果
        return Answer.ok(result.toString());
    }
}
